﻿

namespace JLMiddlewares
{
    public class CustomExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CustomExceptionMiddleware> _logger;

        public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "系统未知异常:");
                await HandleExceptionAsync(httpContext, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
        {
            httpContext.Response.ContentType = "application/json;charset=utf-8";
            httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            return httpContext.Response.WriteAsync("系统未知异常，请联系管理员");
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    //public static class CustomExceptionMiddlewareExtensions
    //{
    //    public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
    //    {
    //        return builder.UseMiddleware<CustomExceptionMiddleware>();
    //    }
    //}
}
